package uk.co.kevinlockwood.kol.droid;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.Log;
import android.view.WindowManager;

public class DroidHelpers {
	private static boolean debug = true;
	private static boolean trace = false;

	public static void printStackTrace(Throwable e) {
		if (null == e) return;
		StackTraceElement[] stes = e.getStackTrace();
		log(e.getClass(),": ",e.getMessage());
		for (StackTraceElement ste : stes) log("\tat ",ste.toString());
		printStackTrace(e.getCause());
	}

	public static void openWebUrl(Activity parent, Uri url) {
		if (null == parent || null == url) return;
		parent.startActivity(new Intent(Intent.ACTION_VIEW, url));
	}

	public static void setupActivity(Activity activity, SharedPreferences settings) {
		if (settings.getBoolean(G.KEEP_SCREEN_ON, Boolean.FALSE)) {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		} else {
			activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}

		if (settings.getBoolean(G.FULL_SCREEN, Boolean.TRUE)) {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		} else {
			activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
	}

	private static String tag = "KOLDROID";
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
	private static synchronized String makeLogString(Object... msg) {
		StringBuilder sb = new StringBuilder();
		sb.append(sdf.format(new Date()));
		sb.append(":: ");
		for (Object o : msg) {
			sb.append(String.valueOf(o));
		}
		return sb.toString();
	}
	public static void log(Object ... msg) {
		Log.i(tag, makeLogString(msg));
	}
	public static void debug(Object ... msg) {
		if (debug) Log.d(tag, makeLogString(msg));
	}
	public static void trace(Object ... msg) {
		if (trace) Log.v(tag, makeLogString(msg));
	}

	public static String getVersion(ContextWrapper self) {
		String version = "unknown";
		try {
			PackageInfo packageInfo = self.getPackageManager().getPackageInfo(self.getPackageName(), 0);
			version = packageInfo.versionName;
		} catch (NameNotFoundException nnfe) {
			printStackTrace(nnfe);
		}
		return version;
	}
}
